package com.promis.pfs;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.promis.okhttp.HttpFileParams;
import com.promis.okhttp.HttpJsonParams;
import com.promis.okhttp.HttpStringParams;
import com.promis.okhttp.JsonNormal;
import com.promis.util.JsonUtils;
import com.promis.util.NetworkUtils;
import com.promis.util.ReflectUtils;
import com.promis.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by jidanbo on 2018/1/24.
 */

public class PfsFileDeleteClient<T> {

    private Context context;
    private static OkHttpClient client = null;

    public PfsFileDeleteClient(Context context) {
        this.context = context;

        if (client == null) {
            client = new OkHttpClient.Builder()
                    .cookieJar(new CookieJar() {
                        private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                        @Override
                        public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                            cookieStore.put(httpUrl.url().getHost(), list);
                        }

                        @Override
                        public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                            List<Cookie> cookies = cookieStore.get(httpUrl.url().getHost());
                            return cookies != null ? cookies : new ArrayList<Cookie>();
                        }
                    })
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();
        }
    }

    public T post(String url, HttpStringParams params) throws IOException {
        RequestBody requestBody = getRequestBody(params);
        return execute(newRequestBuilder(url).addHeader("ParamType", "form").post(requestBody).build());
    }

    private Request.Builder newRequestBuilder(String url) {
        return new Request.Builder().url(url).addHeader("X-Client-Type", "Android").addHeader("AcceptType", "json");
    }

    private RequestBody getRequestBody(HttpStringParams params) {
        return params.getBuilder().build();
    }

    private T execute(Request request) throws IOException {
        String errorMsg;

        if (NetworkUtils.isNetworkConnected(context)) {
            Response response = client.newCall(request).execute();

            if (response.isSuccessful()) {
                final String responseBody = response.body().string();
                return handleResponse(responseBody);
            } else {
                errorMsg = "响应异常：" + response.code() + "," + response.message();
            }
        } else errorMsg = "网络设置异常";
        throw new IOException(errorMsg);
    }

    private T handleResponse(String responseBody) {

        String errorMsg;
        try {
            Type type = ReflectUtils.getSuperclassTypeParameter(getClass());
            T jsonResult = JsonUtils.fromJson(responseBody, type);
            if (JsonNormal.RESULT_LEVEL_SUCCESS.equals(((JsonNormal) jsonResult).getMsgLevel())) {
                return jsonResult;
            } else errorMsg = ((JsonNormal) jsonResult).getMsgContent();
        } catch (Exception ex) {
            errorMsg = "响应数据解析异常" + ex.getMessage();
        }
        throw new RuntimeException(errorMsg);
    }

    public Context getContext() {
        return context;
    }
}
